<?php
/*
 * This file is part of the "nimo-l4" package.
 *
 * (c) Enkhbayasgalan Galsandorj <eegii2you@yahoo.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace nimo\domains\car_balance\controllers;

use BaseController;
use DateTime;
use File;
use Input;
use Mail;
use nimo\domains\car_balance\Model\CarAuction;
use nimo\domains\car_balance\Model\Customer;
use nimo\domains\car_balance\Model\FaxAccount;
use nimo\domains\car_balance\Model\PurchaseCar;
use nimo\domains\car_balance\Model\ServiceCompany;
use nimo\domains\car_balance\Model\CarMaker;
use nimo\domains\master\models\Domain;
use Redirect;
use Request;
use Response;
use Session;
use Str;
use Swift_Attachment;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Validator;
use View;
use Config;
use Sentry;
use Maatwebsite\Excel\Facades\Excel;

class BackofficeController extends BaseController
{
    private $datetime = '';

    protected $validationRules = array(
        "registration_number"                      => "max:40",
        "burtgel_solih"                            => "date",
        "send_export_erasure_to_transport_company" => "date",
        "export_erasure_image"                     => "image|mimes:jpg,jpeg,gif,png|max:3000000",
        "fax_export_erasure_to_auction"            => "date",
        "car_tax_cancel"                           => "date",
        "car_tax_cancel_amount"                    => "integer",
        "car_liability_insurance_cancel"           => "date",
        "car_liability_insurance_cancel_amount"    => "integer",
        "recycle_application_date"                 => "date",
        "recycle"                                  => "date",
        "recycle_fee"                              => "integer",
        "comment"                                  => "max:1000",
    );

    public function documentCarList()
    {
        $query = new PurchaseCar();

        if(Request::has('reset')) {
            Session::forget('document_car_list.filter');
        }
        $lastMonths = array(date("Y-m-01",strtotime("-12 month")),date("Y-m-t"));
        if(Request::isMethod('POST')) {
            // Filter form values to session
            $purchase_date = is_null(Input::get('purchase_date')) ? $lastMonths : explode(' - ',Input::get('purchase_date'));
            Session::put('document_car_list.filter.purchase_date', $purchase_date);
            $car_auction_id = is_null(Input::get('car_auction_id')) ? '0' : Input::get('car_auction_id');
            Session::put('document_car_list.filter.car_auction_id', $car_auction_id);
            $lot_no = is_null(Input::get('lot_no')) ? '0' : Input::get('lot_no');
            Session::put('document_car_list.filter.lot_no', $lot_no);
            $chassis_no = is_null(Input::get('chassis_no')) ? '0' : Input::get('chassis_no');
            Session::put('document_car_list.filter.chassis_no', $chassis_no);
            $registration_number = is_null(Input::get('registration_number')) ? '0' : Input::get('registration_number');
            Session::put('document_car_list.filter.registration_number', $registration_number);
            $shakensyo_flag_cb = is_null(Input::get('shakensyo_flag_cb')) ? '0' : Input::get('shakensyo_flag_cb');
            Session::put('document_car_list.filter.shakensyo_flag_cb', $shakensyo_flag_cb);
            $burtgel_solih_date = is_null(Input::get('burtgel_solih_date')) ? '' : Input::get('burtgel_solih_date');
            Session::put('document_car_list.filter.burtgel_solih_date', $burtgel_solih_date);
            $burtgel_solih = is_null(Input::get('burtgel_solih')) ? '0' : Input::get('burtgel_solih');
            Session::put('document_car_list.filter.burtgel_solih', $burtgel_solih);
            $send_export_erasure_to_transport_company_date = is_null(Input::get('send_export_erasure_to_transport_company_date')) ? '' : Input::get('send_export_erasure_to_transport_company_date');
            Session::put('document_car_list.filter.send_export_erasure_to_transport_company_date', $send_export_erasure_to_transport_company_date);
            $send_export_erasure_to_transport_company = is_null(Input::get('send_export_erasure_to_transport_company')) ? '0' : Input::get('send_export_erasure_to_transport_company');
            Session::put('document_car_list.filter.send_export_erasure_to_transport_company', $send_export_erasure_to_transport_company);
            $car_tax_cancel_date = is_null(Input::get('car_tax_cancel_date')) ? '' : Input::get('car_tax_cancel_date');
            Session::put('document_car_list.filter.car_tax_cancel_date', $car_tax_cancel_date);
            $car_tax_cancel = is_null(Input::get('car_tax_cancel')) ? '0' : Input::get('car_tax_cancel');
            Session::put('document_car_list.filter.car_tax_cancel', $car_tax_cancel);
            $car_liability_insurance_cancel_date = is_null(Input::get('car_liability_insurance_cancel_date')) ? '' : Input::get('car_liability_insurance_cancel_date');
            Session::put('document_car_list.filter.car_liability_insurance_cancel_date', $car_liability_insurance_cancel_date);
            $car_liability_insurance_cancel = is_null(Input::get('car_liability_insurance_cancel')) ? '0' : Input::get('car_liability_insurance_cancel');
            Session::put('document_car_list.filter.car_liability_insurance_cancel', $car_liability_insurance_cancel);
            $recycle_application_date = is_null(Input::get('recycle_application_date')) ? '' : Input::get('recycle_application_date');
            Session::put('document_car_list.filter.recycle_application_date', $recycle_application_date);
            $recycle_application = is_null(Input::get('recycle_application')) ? '0' : Input::get('recycle_application');
            Session::put('document_car_list.filter.recycle_application', $recycle_application);
            $recycle_date = is_null(Input::get('recycle_date')) ? '' : Input::get('recycle_date');
            Session::put('document_car_list.filter.recycle_date', $recycle_date);
            $recycle = is_null(Input::get('recycle')) ? '0' : Input::get('recycle');
            Session::put('document_car_list.filter.recycle', $recycle);
            $comment = is_null(Input::get('comment')) ? '0' : Input::get('comment');
            Session::put('document_car_list.filter.comment', $comment);
            $purchase_car_id = is_null(Input::get('purchase_car_id')) ? '' : Input::get('purchase_car_id');
            Session::put('document_car_list.filter.purchase_car_id', $purchase_car_id);
        } else {
            // Filter values from session
            $purchase_date = Session::get('document_car_list.filter.purchase_date', $lastMonths);
            $car_auction_id = Session::get('document_car_list.filter.car_auction_id', '0');
            $lot_no = Session::get('document_car_list.filter.lot_no', '0');
            $chassis_no = Session::get('document_car_list.filter.chassis_no', '0');
            $registration_number = Session::get('document_car_list.filter.registration_number', '0');
            $shakensyo_flag_cb = Session::get('document_car_list.filter.shakensyo_flag_cb', '0');
            $burtgel_solih_date = Session::get('document_car_list.filter.burtgel_solih_date', '');
            $burtgel_solih = Session::get('document_car_list.filter.burtgel_solih', '0');
            $send_export_erasure_to_transport_company_date = Session::get('document_car_list.filter.send_export_erasure_to_transport_company_date', '');
            $send_export_erasure_to_transport_company = Session::get('document_car_list.filter.send_export_erasure_to_transport_company', '0');
            $car_tax_cancel_date = Session::get('document_car_list.filter.car_tax_cancel_date', '');
            $car_tax_cancel = Session::get('document_car_list.filter.car_tax_cancel', '0');
            $car_liability_insurance_cancel_date = Session::get('document_car_list.filter.car_liability_insurance_cancel_date', '');
            $car_liability_insurance_cancel = Session::get('document_car_list.filter.car_liability_insurance_cancel', '0');
            $recycle_application_date = Session::get('document_car_list.filter.recycle_application_date', '');
            $recycle_application = Session::get('document_car_list.filter.recycle_application', '0');
            $recycle_date = Session::get('document_car_list.filter.recycle_date', '');
            $recycle = Session::get('document_car_list.filter.recycle', '0');
            $comment = Session::get('document_car_list.filter.comment', '0');
            $purchase_car_id = Session::get('document_car_list.filter.purchase_car_id', '');
        }

        // Applying filters
        if(count($purchase_date) >1 )
            $query = $query->whereBetween('purchase_date', array(date('Y-m-d', strtotime($purchase_date[0])),date('Y-m-d', strtotime($purchase_date[1]))));
        if($car_auction_id != '0')
            $query = $query->where('auction_name', '=', $car_auction_id);
        if($lot_no != 0)
            $query = $query->where('lot_no', '=', $lot_no);
        if($chassis_no != '0')
            $query = $query->where('chasis_no', 'like', "%$chassis_no");
        if($registration_number)
            $query = $query->where('registration_number', 'like', "%$registration_number%");
        if($shakensyo_flag_cb != '0') {
            $query = $query->where('shakensyo_flag', '=', '1');
        }
        if($purchase_car_id)
            $query = $query->where('id', '=', $purchase_car_id);
        if($burtgel_solih != '0') {
            $query = $query->whereNull('burtgel_solih');
        }
        elseif($burtgel_solih_date != '') {
            $query = $query->where('burtgel_solih', '>=', date('Y-m-d', strtotime($burtgel_solih_date)));
        }
        if($send_export_erasure_to_transport_company != '0') {
            $query = $query->whereNull('send_export_erasure_to_transport_company');
        }
        elseif($send_export_erasure_to_transport_company_date != '') {
            $query = $query->where('send_export_erasure_to_transport_company', '>=', date('Y-m-d', strtotime($send_export_erasure_to_transport_company_date)));
        }
        if($car_tax_cancel != '0') {
            $query = $query->whereNull('car_tax_cancel');
        }
        elseif($car_tax_cancel_date != '') {
            $query = $query->where('car_tax_cancel', '>=', date('Y-m-d', strtotime($car_tax_cancel_date)));
        }
        if($car_liability_insurance_cancel != '0') {
            $query = $query->whereNull('car_liability_insurance_cancel');
        }
        elseif($car_liability_insurance_cancel_date != '') {
            $query = $query->where('car_liability_insurance_cancel', '>=', date('Y-m-d', strtotime($car_liability_insurance_cancel_date)));
        }
        if($recycle_application != '0') {
            $query = $query->whereNull('recycle_application_date');
        }
        elseif($recycle_application_date != '') {
            $query = $query->where('recycle_application_date', '>=', date('Y-m-d', strtotime($recycle_application_date)));
        }
        if($recycle != '0') {
            $query = $query->whereNull('recycle');
        }
        elseif($recycle_date != '') {
            $query = $query->where('recycle', '>=', date('Y-m-d', strtotime($recycle_date)));
        }
        if($comment)
            $query = $query->where('document_comment', 'like', "%$comment%");

        $count = $query->count();
        $perpage = Request::has('perpage') ? Request::get('perpage') : 30;
        $page = Request::has('page') ? Request::get('page') : 1;
        $total_page = ($count / $perpage) + (($count % $perpage > 0)? 1: 0);
        $pagination = array('total_page' => $total_page, 'perpage' => $perpage, 'page' => $page);

        // QUERY ORDER
        $query = $query->orderBy('purchase_date', 'desc');
        if($burtgel_solih_date != '')
            $query = $query->orderBy('burtgel_solih', 'desc');
        if($send_export_erasure_to_transport_company_date != '')
            $query = $query->orderBy('send_export_erasure_to_transport_company', 'desc');
        if($car_tax_cancel_date != '')
            $query = $query->orderBy('car_tax_cancel', 'desc');
        if($car_liability_insurance_cancel_date != '')
            $query = $query->orderBy('car_liability_insurance_cancel', 'desc');
        if($recycle_application_date != '')
            $query = $query->orderBy('recycle_application_date', 'desc');
        if($recycle_date != '')
            $query = $query->orderBy('recycle', 'desc');
            
        //$cars = $query->with('customer')->with('vanningCompany')->with('carAuction')->with('serviceCompany')->paginate($perpage);
        $cars = $query->paginate($perpage);

        $filters = array(
            'purchase_date' => $purchase_date,
            'car_auction_id' => $car_auction_id,
            'lot_no' => $lot_no,
            'chassis_no' => $chassis_no,
            'registration_number' => $registration_number,
            'shakensyo_flag_cb' => $shakensyo_flag_cb,
            'burtgel_solih_date' => $burtgel_solih_date,
            'burtgel_solih' => $burtgel_solih,
            'send_export_erasure_to_transport_company_date' => $send_export_erasure_to_transport_company_date,
            'send_export_erasure_to_transport_company' => $send_export_erasure_to_transport_company,
            'car_tax_cancel_date' => $car_tax_cancel_date,
            'car_tax_cancel' => $car_tax_cancel,
            'car_liability_insurance_cancel_date' => $car_liability_insurance_cancel_date,
            'car_liability_insurance_cancel' => $car_liability_insurance_cancel,
            'recycle_application_date' => $recycle_application_date,
            'recycle_application' => $recycle_application,
            'recycle_date' => $recycle_date,
            'recycle' => $recycle,
            'comment' => $comment,
            'purchase_car_id' => $purchase_car_id,
        );

        //$car_makers = array_merge(array(''),Domain::where('name', '=', 'car_type')->first()->immediateDescendants(array('name','name2'))->lists('name', 'name2'));
        //$car_types = array_merge(array(''),Domain::where('name', '=', 'car_type')->first()->immediateDescendants(array('name','name2'))->lists('name', 'name2'));

        return View::make('nimo.domains.car_balance.Main.document_car_list')
            ->with('cars', $cars)
            ->with('filters', $filters)
            //->with('service_company_list', array_merge(array('0' => 'All Service company'), ServiceCompany::lists('name', 'id')))
            //->with('customer_list', array_merge(array('0' => 'All Customer'), Customer::lists('name', 'id')))
            //->with('car_maker_list', array_combine($car_makers, $car_makers))
            ->with('car_auction_list', array_merge(array('0' => 'All Auction'), CarAuction::lists('name', 'id')))
            ->with('pagination', $pagination)
            ;
    }

    public function documentStatus($id = null)
    {
        $car = PurchaseCar::findOrFail($id);

        return View::make('nimo.domains.car_balance.Main.backoffice')
            ->with('car', $car)
            ;
    }

    /*public function setStatus($id = null)
    {
        $car = PurchaseCar::findOrFail($id);

        $field = Input::get('field');
        $status = Input::get('status');

        $car->{$field} = $status;
        $car->save();

        return Response::json(array('status' => 'ok', 'field' => $field, 'value' => $car->{$field}));
    }*/

    /**
     * Car document edit form processing.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function setStatus($id = null)
    {
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar document page
            return Redirect::route('car_balance.main.document_car_list')->with('error', "Car [$id] does not exist.");
        }

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRules);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        $file = Input::file('export_erasure_image');
        if($file) {
            $destinationPath = Config::get('app.uploads.export_cert');
            $filename = strtoupper($purchase_car->chasis_no).'.jpg'; // str_random(8).$file->getClientOriginalName();

            $upload_success = Input::file('export_erasure_image')->move($destinationPath, $filename);

            if( $upload_success ) {
                //$purchase_car->mail_export_erasure_to_nmc = '/uploads/'.$filename;
                $purchase_car->mail_export_erasure_to_nmc_upload_flag = true;
            } else {
                $purchase_car->mail_export_erasure_to_nmc_upload_flag = false;
            }
        }
        // Update the purchase_car data
        //var_dump(Input::get('registration_number')); die;
        $purchase_car->registration_number = e(Input::get('registration_number'));
        if (e(Input::get('number_arrival_flag')) == 'on') {
            $purchase_car->number_arrival_flag = true;
        } else {
            $purchase_car->number_arrival_flag = false;
        }
        if (e(Input::get('burtgel_solih'))) {
            $purchase_car->burtgel_solih = e(date('Y-m-d', strtotime(Input::get('burtgel_solih'))));
        } else {
            $purchase_car->burtgel_solih = null;
        }
        if (e(Input::get('send_export_erasure_to_transport_company'))) {
            $purchase_car->send_export_erasure_to_transport_company = e(date('Y-m-d', strtotime(Input::get('send_export_erasure_to_transport_company'))));
        } else {
            $purchase_car->send_export_erasure_to_transport_company = null;
        }
        if (e(Input::get('fax_export_erasure_to_auction'))) {
            $purchase_car->fax_export_erasure_to_auction = e(date('Y-m-d', strtotime(Input::get('fax_export_erasure_to_auction'))));
        } else {
            $purchase_car->fax_export_erasure_to_auction = null;
        }
        if (e(Input::get('car_tax_cancel'))) {
            $purchase_car->car_tax_cancel = e(date('Y-m-d', strtotime(Input::get('car_tax_cancel'))));
        } else {
            $purchase_car->car_tax_cancel = null;
        }
        $purchase_car->car_tax_cancel_amount                        = e(Input::get('car_tax_cancel_amount'));
        if (e(Input::get('car_liability_insurance_cancel'))) {
            $purchase_car->car_liability_insurance_cancel = e(date('Y-m-d', strtotime(Input::get('car_liability_insurance_cancel'))));
        } else {
            $purchase_car->car_liability_insurance_cancel = null;
        }
        $purchase_car->car_liability_insurance_cancel_amount        = e(Input::get('car_liability_insurance_cancel_amount'));
        if (e(Input::get('recycle_application_date'))) {
            $purchase_car->recycle_application_date = e(date('Y-m-d', strtotime(Input::get('recycle_application_date'))));
        } else {
            $purchase_car->recycle_application_date = null;
        }
        if (e(Input::get('recycle'))) {
            $purchase_car->recycle = e(date('Y-m-d', strtotime(Input::get('recycle'))));
        } else {
            $purchase_car->recycle = "";
        }
        $purchase_car->returned_recycle                             = e(Input::get('returned_recycle'));
        $purchase_car->document_comment                             = e(Input::get('document_comment'));
        //$purchase_car->export_erasure                               = e(Input::get('burtgel_solih'));
        //$purchase_car->send_export_erasure_to_transport_company_fee = e(Input::get('send_export_erasure_to_transport_company_fee'));
        //$purchase_car->mail_export_erasure_to_nmc                   = e(Input::get('mail_export_erasure_to_nmc'));
        //$purchase_car->mail_export_erasure_to_nmc_upload_flag       = e(Input::get('mail_export_erasure_to_nmc_upload_flag'));

        // Was the purchase_car updated?
        if($purchase_car->save())
        {
            // Redirect to the PurchaseCar page
            Session::get('document_car_list.filter');
            return Redirect::route('car_balance.main.document_car_list')->with('success', 'Purchase car document status edited successfully');
        }

        // Redirect to the PurchaseCar expense management page
        return Redirect::route('car_balance.main.backoffice', array('id' => $purchase_car->id))->with('error', 'Error occurred, please try again.');
    }

    public function setShakensyo()
    {
        $id = Request::get('carId');
        $status = Request::get('status');

        $car = PurchaseCar::findOrFail($id);

        if ($status == 'true') {
            $car->shakensyo_flag = true;
        }
        else {
            $car->shakensyo_flag = false;
        }

        $car->save();

        return Response::json(array('status' => 'shakensyo flag ok'));
    }

    public function setNumberArrival()
    {
        $id = Request::get('carId');
        $status = Request::get('status');

        $car = PurchaseCar::findOrFail($id);

        if ($status == 'true') {
            $car->number_arrival_flag = true;
        }
        else {
            $car->number_arrival_flag = false;
        }

        $car->save();

        return Response::json(array('status' => 'number arrival flag ok'));
    }

    public function getRecycle()
    {
        return View::make('nimo.domains.car_balance.Main.getRecycle')
            ->with('success_car', array());

    }

    public function postRecycle()
    {
        $csvFile = Input::file('recycle_upload');
        if($csvFile) {
            $destinationPath = Config::get('app.uploads.recycle');
            $filename = strtoupper(e(Input::get('recycle_return_date'))).'.csv'; // str_random(8).$file->getClientOriginalName();

            $upload_success = Input::file('recycle_upload')->move($destinationPath, $filename);

            $csvFile = fopen($destinationPath.$filename, "r");
            $success_car = array();
            $i = 0;
            $recycle = 0;
            $row = 1;
            while (($data = fgetcsv($csvFile, 1000, ",")) !== FALSE) {
                $num = count($data);
                for ($c=0; $c < $num; $c++) {
                    if ($row == 2) {
                        if ($c == 3) {
                            if (!((str_replace('/', '', $data[3]).'01') == date('Ymd', strtotime(e(Input::get('recycle_return_date')))))) {
                                return Redirect::back()->with('error', 'Recycle Return date CSV-giin date-s uur bn, please try again.');
                            }
                        }
                        if ($c == 4) {
                            $recycle = str_replace('/', '-', $data[4]);
                        }
                    }
                    if ($row > 4 && $c == 2) {
                        if (is_null($purchase_car = PurchaseCar::where('chasis_no', '=', $data[$c])->first())) {
                            $success_car[mb_convert_encoding($data[$c], "UTF-8", "Shift-JIS")] = $data[9];
                        } else {
                            $purchase_car->returned_recycle = $data[9];
                            $purchase_car->recycle = $recycle;
                            $purchase_car->save();
                            $success_car[$purchase_car->chasis_no] = 1;
                        }
                    }
                }
                $row++;
            }
        }
        return View::make('nimo.domains.car_balance.Main.getRecycle')
            ->with('success', 'CSV file was successfully upload.')
            ->with('success_car', $success_car);
    }


    public function exportCarList()
    {
        return View::make('nimo.domains.car_balance.Main.export_car_list');
    }

    /**
     *
     */
    public function exportCarListXls()
    {
        $cars = PurchaseCar::all();

        Excel::create('export_purchase_car')
            -> sheet('Purchase car')
            -> with($cars->toArray())
            -> export('xls');
    }

    public function importCarList()
    {
        return View::make('nimo.domains.car_balance.Main.import_car_list')
            ->with('success_car', array());

    }

    public function importCarListXls()
    {
        $importFile = Input::file('purchase_car_upload');
        $success_car = array();
        $this->datetime = new DateTime('now');
        $this->datetime->format('Y-m-d-H-M-s');
        if($importFile) {
            Excel::load($importFile, function($readers) {
                $readers->each(function($reader) {
                    if ($reader->update_flag == 'u') {
                        $purchase_car = PurchaseCar::where('id', '=', $reader->id)->first();
                        $success_car[$reader->id] = 1;
                        $purchase_car->payment_total_amount = $reader->payment_total_amount;
                        $purchase_car->purchase_price       = $reader->purchase_price;
                        $purchase_car->vat_percent          = $reader->vat_percent;
                        $purchase_car->recycle_amount       = $reader->recycle_amount;
                        $purchase_car->auction_commission   = $reader->auction_commission;
                        $purchase_car->car_tax_amount       = $reader->car_tax_amount;
                        $purchase_car->tic_send_fee         = $reader->tic_send_fee;
                        $purchase_car->transfer_fee         = $reader->transfer_fee;
                        $purchase_car->others               = $reader->others;
                        $purchase_car->vanning              = $reader->vanning;
                        $purchase_car->container_id         = $reader->container_id;
                        $purchase_car->container_date       = $reader->container_date;
                        $purchase_car->container_no         = $reader->container_no;
                        $purchase_car->bill_total_amount    = $reader->bill_total_amount;
                        $purchase_car->bill_price           = $reader->bill_price;
                        $purchase_car->bill_vat             = $reader->bill_vat;
                        $purchase_car->bill_recycle         = $reader->bill_recycle;
                        $purchase_car->bill_rakusatu        = $reader->bill_rakusatu;
                        $purchase_car->bill_transport_fee   = $reader->bill_transport_fee;
                        $purchase_car->bill_vanning         = $reader->bill_vanning;
                        $purchase_car->bill_others          = $reader->bill_others;
                        $purchase_car->bill_commission      = $reader->bill_commission;
                        $purchase_car->return_vat           = $reader->return_vat;
                        $purchase_car->return_vat_nmh       = $reader->return_vat_nmh;
                        $purchase_car->return_vat_tic       = $reader->return_vat_tic;
                        $purchase_car->return_vat_kg        = $reader->return_vat_kg;
                        $purchase_car->return_recycle       = $reader->return_recycle;
                        $purchase_car->return_recycle_nmh   = $reader->return_recycle_nmh;
                        $purchase_car->return_recycle_tic   = $reader->return_recycle_tic;
                        $purchase_car->return_car_tax       = $reader->return_car_tax;
                        $purchase_car->tic_commission       = $reader->tic_commission;
                        $purchase_car->return_liability     = $reader->return_liability;
                        $purchase_car->return_weight_tax    = $reader->return_weight_tax;
                        $purchase_car->auction_penalty      = $reader->auction_penalty;
                        $purchase_car->updated_at           = $this->datetime;
                        $purchase_car->save();
                    }
                });
            });
        }

        $query = new PurchaseCar();
        $query = $query->select('chasis_no');
        $query = $query->where('updated_at', '=', $this->datetime);

        return View::make('nimo.domains.car_balance.Main.import_car_list')
            ->with('success', 'Excel file was successfully upload.')
            ->with('success_car', $query->get());
    }

    public function faxTransmissionList()
    {
        $query = new PurchaseCar();

        if(Request::has('reset')) {
            Session::forget('fax_transmission_list.filter');
        }

        if(Request::isMethod('POST')) {
            // Filter form values to session
            $chassis_no = is_null(Input::get('chassis_no')) ? '0' : Input::get('chassis_no');
            Session::put('fax_transmission_list.filter.chassis_no', $chassis_no);
            $number_plate_flag_cb = is_null(Input::get('number_plate_flag_cb')) ? '0' : Input::get('number_plate_flag_cb');
            Session::put('fax_transmission_list.filter.number_plate_flag_cb', $number_plate_flag_cb);
            $burtgel_solih_date = is_null(Input::get('burtgel_solih_date')) ? '' : Input::get('burtgel_solih_date');
            Session::put('fax_transmission_list.filter.burtgel_solih_date', $burtgel_solih_date);
            $burtgel_solih = is_null(Input::get('burtgel_solih')) ? '0' : Input::get('burtgel_solih');
            Session::put('fax_transmission_list.filter.burtgel_solih', $burtgel_solih);
            $fax_export_erasure_to_auction_date = is_null(Input::get('fax_export_erasure_to_auction_date')) ? '' : Input::get('fax_export_erasure_to_auction_date');
            Session::put('fax_transmission_list.filter.fax_export_erasure_to_auction_date', $fax_export_erasure_to_auction_date);
            $fax_export_erasure_to_auction = is_null(Input::get('fax_export_erasure_to_auction')) ? '0' : Input::get('fax_export_erasure_to_auction');
            Session::put('fax_transmission_list.filter.fax_export_erasure_to_auction', $fax_export_erasure_to_auction);
        } else {
            // Filter values from session
            $chassis_no = Session::get('fax_transmission_list.filter.chassis_no', '0');
            $number_plate_flag_cb = Session::get('fax_transmission_list.filter.number_plate_flag_cb', 'on');
            $burtgel_solih_date = Session::get('fax_transmission_list.filter.burtgel_solih_date', '');
            $burtgel_solih = Session::get('fax_transmission_list.filter.burtgel_solih', '0');
            $fax_export_erasure_to_auction_date = Session::get('fax_transmission_list.filter.fax_export_erasure_to_auction_date', '');
            $fax_export_erasure_to_auction = Session::get('fax_transmission_list.filter.fax_export_erasure_to_auction', 'on');
        }

        // Applying filters
        if($chassis_no != '0' && !empty($chassis_no) )
            $query = $query->where('chasis_no', 'like', "%$chassis_no");
        if($number_plate_flag_cb != '0') {
            $query = $query->where('number_plate_flag', '=', '1');
        }

        if($burtgel_solih == 'on') {
            $query = $query->whereNull('burtgel_solih');
        }
        else {
            if($burtgel_solih_date != '') {
                $query = $query->where('burtgel_solih', '>=', date('Y-m-d', strtotime($burtgel_solih_date)));
            }
            else {
                $query = $query->whereNotNull('burtgel_solih');
            }
        }

        if($fax_export_erasure_to_auction != '0') {
            $query = $query->whereNull('fax_export_erasure_to_auction');
        }
        elseif($fax_export_erasure_to_auction_date != '') {
            $query = $query->where('fax_export_erasure_to_auction', '>=', date('Y-m-d', strtotime($fax_export_erasure_to_auction_date)));
        }

        $perpage = Request::has('perpage') ? Request::get('perpage') : 30;
        $count = $query->count();
        $page = Request::has('page') ? Request::get('page') : 1;
        $total_page = ($count / $perpage) + (($count % $perpage > 0)? 1: 0);
        $pagination = array('total_page' => $total_page, 'perpage' => $perpage, 'page' => $page);
        
        // QUERY ORDER
        $query = $query->orderBy('purchase_date', 'desc');
        if($burtgel_solih_date != '')
            $query = $query->orderBy('burtgel_solih', 'desc');
        if($fax_export_erasure_to_auction_date != '')
            $query = $query->orderBy('fax_export_erasure_to_auction', 'desc');


        //$cars = $query->with('customer')->with('vanningCompany')->with('carAuction')->with('serviceCompany')->paginate($perpage);
        $cars = $query->paginate($perpage);

        $filters = array(
            'chassis_no' => $chassis_no,
            'number_plate_flag_cb' => $number_plate_flag_cb,
            'burtgel_solih_date' => $burtgel_solih_date,
            'burtgel_solih' => $burtgel_solih,
            'fax_export_erasure_to_auction_date' => $fax_export_erasure_to_auction_date,
            'fax_export_erasure_to_auction' => $fax_export_erasure_to_auction,
        );

        return View::make('nimo.domains.car_balance.Main.fax_transmission_list')
            ->with('cars', $cars)
            ->with('filters', $filters)
            ->with('fax_account_list', FaxAccount::lists('sender', 'id'))
            ->with('pagination', $pagination)
            ;
    }

    /**
     * PurchaseCar create.
     *
     * @return View
     */
    public function faxSend()
    {
        Session::forget('success_car');

        $this->checkPermission(array('admin'));

        $cars = Request::get('cars');
        $sender = Request::get('sender');
        $subject = Request::get('subject');
        $email_body = Request::get('email_body');
        $email_body = str_replace('。', '。'.PHP_EOL, $email_body);
        $email_body = str_replace('バー', 'バー'.PHP_EOL, $email_body);
        $email_signature = Request::get('email_signature');
        $success_car = array();
        $tabStr = '&nbsp;&nbsp;&nbsp;&nbsp;';

        $fax_account = FaxAccount::findOrFail($sender);

        $transport = Swift_SmtpTransport::newInstance($fax_account->email_host, $fax_account->email_protocol, $fax_account->email_encryption)
            ->setUsername($fax_account->email)
            ->setPassword($fax_account->email_password)
        ;

        $mailSubject = $subject;
        $mailFrom = $fax_account->email;
        $mailSender = $fax_account->sender;

        $mailer = Swift_Mailer::newInstance($transport);
        Mail::setSwiftMailer($mailer);

        $query = new PurchaseCar();
        $query = $query->whereIn('id', $cars);
        $query = $query->orderBy('purchase_date', 'asc');
        $cars = $query->get();

        foreach ($cars as $car) {
            if (is_null($car->carAuction->name)) {
                $success_car[$car->chasis_no] = $car->carAuction->name;
            }
            else {
                if (substr($fax_account->efax_service, 0, 1) == '@') {
                    $mailTo  = ($car->carAuction->fax).($fax_account->efax_service);
                } else {
                    $mailTo  = $fax_account->efax_service;
                }
                $data = array(
                    'email_body' => $email_body,
                    'car' => $car->purchase_date.($tabStr).$car->lot_no.($tabStr).$car->car_maker.($tabStr).$car->car_name.($tabStr).$car->chasis_no.($tabStr).$car->registration_number,
                    'email_signature' => $email_signature,
                );

                if ($car->mail_export_erasure_to_nmc_upload_flag) {
                    $dir = Config::get('app.uploads.export_cert');
                    $file = $car->chasis_no.'.jpg';
                    $pathToFile = $dir.$file;
                }
                else {
                    $pathToFile = null;
                }

                Mail::send('nimo.domains.car_balance.Main.fax_send', $data, function($m) use ($mailFrom, $mailSender, $mailSubject, $mailTo, $pathToFile)
                {
                    $m->from($mailFrom, $mailSender);
                    $m->to($mailTo);
                    $m->subject($mailSubject);
                    if ($pathToFile){
                        $m->attach($pathToFile, array('mime' => 'image/jpg'));
                    }

                });
                $success_car[$car->chasis_no] = 1;
                $today = new DateTime('now');
                $car->fax_export_erasure_to_auction = $today->format('Y-m-d');
                $car->save();
            }
        }
        Session::put('success_car', $success_car);

        return Response::json(array('status'=>'Successfully send fax.', 'success_car' => $success_car));
    }

    public function getFaxDetial()
    {
        $id = Request::get('id');
        $fax_account = FaxAccount::findOrFail($id);
        return Response::json(array('fax_subject' => $fax_account->subject, 'fax_body' => $fax_account->email_body, 'fax_signature' => $fax_account->email_signature));
    }
}